<script setup lang="ts">
import { ref, computed } from 'vue'
import type { Ref, ComputedRef } from 'vue'
import { getSendMsgCode, getCheckCode } from '@/api/user'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'


// this.$router  = router
// this.$route   = route
const router = useRouter()
const route = useRoute()

// tel 就是用户输入的手机号
const telcode: Ref<string> = ref('')





// 点击发送验证码
let time: Ref<number> = ref(10)
let text: Ref<string> = ref('发送验证码')
let timer: Ref<any> = ref(null)
function sendCodeFn() {

  // 先清除掉上一次的定时器
  clearInterval(timer.value)

  // 发送验证码，发完验证码就要写一个定时器进行倒计时

  getSendMsgCode({ tel: localStorage.getItem('tel') || '' }).then(res => {
    console.log(res.data);

    timer.value = setInterval(() => {
      text.value = '重新获取(' + time.value + 's)'
      time.value--
      if (time.value == -1) {
        // 关闭定时器
        clearInterval(timer.value)
        // 将按钮设置为 发送验证码
        time.value = 10
        text.value = '发送验证码'
      }
    }, 1000)
  })


}


// 如果验证码长度不够就不能点击下一步
const flag = computed(() => {
  return telcode.value.length < 5
})

// 点击进入 step3
function checkTel() {

  // 先来验证我们输入的验证码是否正确
  getCheckCode({
    tel: localStorage.getItem('tel') || '',
    telcode: telcode.value
  }).then(res => {
    console.log(res);
    if (res.data.code == '10007') {
      // 验证码错误
      showToast('验证码错误')
    } else {
      // 验证码正确
      showToast('验证码正确')
      router.push('/register/step3')
    }
  })




  // router.push('/register/step3')
}

</script>
<template>
  <div class="my-box">
    <div class="my-cell">
      <van-field v-model="telcode" label="验证码" placeholder="请输入验证码">
        <template #button>
          <van-button size="mini" :disabled="time < 10" @click="sendCodeFn">{{ text }}</van-button>
        </template>
      </van-field>
    </div>

    <div class="my-button">
      <van-button type="danger" :disabled="flag" block @click="checkTel">下一步</van-button>
    </div>
  </div>
</template>
<style scoped lang="scss">
.my-box {
  padding: 50px 20px;
  box-sizing: border-box;
}

.my-cell {
  border: 1px solid gray;
}

.my-button {
  margin-top: 30px;
}
</style>
